package nl.grol.yakshop.domain.service;

import java.util.List;
import java.util.logging.Logger;

import nl.grol.yakshop.domain.model.ProcessedOrder;
import nl.grol.yakshop.domain.model.Stock;
import nl.grol.yakshop.domain.model.YakHerd;
import nl.grol.yakshop.domain.repository.RepositoryI;
import nl.grol.yakshop.util.YakShopException;

import com.google.inject.Inject;

public class StockCalculator implements StockCalculatorI {
    private static final Logger LOGGER = Logger.getLogger(StockCalculator.class.getName());

    private RepositoryI repository;
	private ProductionCalculatorI productionCalculator;

	@Inject
	public StockCalculator(RepositoryI repository, ProductionCalculatorI calculator) {
		this.repository =  repository;
		this.productionCalculator = calculator;
	}

	@Override
	public Stock determineStockOnDay( int dayOffsetSinceShopOpening ) throws YakShopException {
		
		/*
		 * Get data
		 */
		YakHerd herd = repository.getHerd();
		
		// logit
//		for( YakI yak : herd.getYaks() ) {
//			log.info(yak.toString() );
//		}

		/*
		 * Calculate current stock
		 */
		double totalMilkInStock = productionCalculator.calculateHerdMilkProductionSofar(herd.getYaks(), dayOffsetSinceShopOpening);
		int totalSkinsInStock = productionCalculator.calculateHerdSkinProductionSofar(herd.getYaks(), dayOffsetSinceShopOpening);
//		log.info("Milk in stock:"+ totalMilkInStock );
//		log.info("Skins in stock:"+ totalSkinsInStock );
		
		/*
		 * Fetch orders
		 */
		double milkOrderedSofar = 0.0;
		int skinsOrderedSofar = 0;
		List<ProcessedOrder> orders = 
			repository.getProcessedOrdersBeforeDay(dayOffsetSinceShopOpening);
		for( ProcessedOrder order : orders ) {
			/*
			 * Subtract orders from stock
			 */
			if( order.getMilkInLiters() != null ) {
				milkOrderedSofar += order.getMilkInLiters().doubleValue();
			}
			if( order.getSkins() != null ) {
				skinsOrderedSofar += order.getSkins().intValue();
			}
		}
//		log.info("Milk ordered sofar:"+ milkOrderedSofar );
//		log.info("Skins ordered sofar:"+ skinsOrderedSofar );
		
		/*
		 * Compose stock object
		 */
		Stock stock = new Stock( dayOffsetSinceShopOpening, 
					totalMilkInStock-milkOrderedSofar, 
					totalSkinsInStock-skinsOrderedSofar );
		
//		log.info("stock:" + stock );
		
		return stock;
		
	}
}
